#include "tcpServer.h"
#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<cstring>
#include<arpa/inet.h>

void TcpServer::connectServer(const char *ip, int port)
{
    //创建通信文件描述符
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd == -1)
    {
        perror("socket create error:");
        _exit(-1);
    }

    //连接服务器
    sockaddr_in serverAddress;
    memset(&serverAddress,0,sizeof(serverAddress));
    //地址族
    serverAddress.sin_family = AF_INET; //ipv4
    //端口
    serverAddress.sin_port = htons(port);
    //服务器IP
    const char * serverIp = ip;
    inet_pton(AF_INET,serverIp,&(serverAddress.sin_addr.s_addr));
    //连接服务器
    int ret = connect(sockfd,(const sockaddr *)&serverAddress,sizeof(serverAddress));
    if(ret == -1)
    {
        perror("connect error ");
        exit(1);
    }

    m_connfd = sockfd;


}

int TcpServer::sendMessage(const void *sendMsg, size_t size)
{
    int writeByts = write(m_connfd,&size,sizeof(size_t));
    writeByts =  write(m_connfd,sendMsg,size);
    return writeByts;
}

int TcpServer::sendMessage(const std::string &sendMsg)
{
    return sendMessage(sendMsg.c_str(),sendMsg.length());
}

int TcpServer::recvMessage(void *buf, size_t size)
{
    return 0;
}

int TcpServer::recvMessage(std::string &recvMsg)
{
    size_t datasize = 0;
    int readByts = read(m_connfd,&datasize,sizeof(size_t));
    if(readByts < 0)
    {
        perror("read error");
        return -1;
    }
    char * msg = new char[datasize + 1];
    

}

void TcpServer::setAttrConnfd(int connfd)
{

}
